package com.egene.tw.activity.signs.measure;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.egene.tw.R;
import com.egene.tw.activity.signs.BaseMeasureActivity;
import com.egene.tw.activity.signs.blood.BloodActivity_;
import com.egene.tw.activity.signs.fatigue.FatigueActivity_;
import com.egene.tw.activity.signs.heart.HeartActivity_;
import com.egene.tw.activity.signs.oxygen.OxygenActivity_;
import com.egene.tw.blue.BluetoothLeServiceV2;
import com.egene.tw.bus.BusHelper;
import com.egene.tw.bus.LoadDataEndEvent;
import com.egene.tw.bus.MeasureEndEvent;
import com.egene.tw.data.DataRepository;
import com.egene.tw.data.RealmHelper;
import com.egene.tw.data.entity.BloodData;
import com.egene.tw.data.entity.DeviceSetting;
import com.egene.tw.data.entity.FatigueData;
import com.egene.tw.data.entity.HeartData;
import com.egene.tw.data.entity.OxygenData;
import com.egene.tw.data.utils.CalUtils;
import com.egene.tw.data.wrapper.HomeData;
import com.egene.tw.data.wrapper.OneKeyMeasureData;
import org.greenrobot.eventbus.Subscribe;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;

@EActivity(R.layout.activity_measure)
public class MeasureActivity extends BaseMeasureActivity {
    private int heart;
    private int oxygen;
    private int bloodHigh;
    private int bloodLow;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusHelper.register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusHelper.unRegister(this);
    }

    //ToolBar Views
    @ViewById(R.id.actionBar)
    Toolbar mToolbarView;
    @ViewById(R.id.toolbar_title)
    TextView mToolBarTitle;


    @ViewById(R.id.textLastTime)
    TextView textLastTime;

    @ViewById(R.id.btnStart)
    TextView btnStart;

    @ViewById(R.id.textHeart)
    TextView textHeart;
    @ViewById(R.id.textOxygen)
    TextView textOxygen;
    @ViewById(R.id.textBloodHigh)
    TextView textBloodHigh;
    @ViewById(R.id.textBloodLow)
    TextView textBloodLow;
    @ViewById(R.id.textFatigue)
    TextView textFatigue;


    @ViewById(R.id.measureTips)
    View measureTips;


    @AfterViews
    void initViews() {
        mToolbarView.setNavigationIcon(R.drawable.ic_back);
        mToolbarView.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        loadSetting();
        initBle();
//        getList();
    }

    @Click(R.id.viewMeasure)
    void measure() {
        String deviceAddress = RealmHelper.getDeviceAddress();
        if (TextUtils.isEmpty(deviceAddress)) {
            Toast.makeText(this, R.string.status_un_bind, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!BluetoothLeServiceV2.connected) {
            Toast.makeText(this, R.string.status_disconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        btnStart.setText(R.string.measureing);
        oneKeyMeasure();
    }

    @Click(R.id.viewHeart)
    void viewHeart() {
        Intent intent = new Intent(this, HeartActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.viewBlood)
    void viewBlood() {
        Intent intent = new Intent(this, BloodActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.viewOxygen)
    void viewOxygen() {
        Intent intent = new Intent(this, OxygenActivity_.class);
        startActivity(intent);
    }

    @Click(R.id.viewFatigue)
    void viewFatigue() {
        Intent intent = new Intent(this, FatigueActivity_.class);
        startActivity(intent);
    }

//
//    @Subscribe
//    public void onEvent(LoadDataEndEvent data) {
//        getList();
//    }

    @Subscribe
    public void onEvent(OneKeyMeasureData data) {
        if (data.getHeart() != 0) {
            heart = data.getHeart();
        }
        if (data.getOxygen() != 0) {
            oxygen = data.getOxygen();
        }
        if (data.getBloodHigh() != 0) {
            bloodHigh = data.getBloodHigh();
        }
        if (data.getBloodLow() != 0) {
            bloodLow = data.getBloodLow();
        }
        textHeart.setText("" + heart);
        textOxygen.setText("" + oxygen);
        textBloodHigh.setText("" + bloodHigh);
        textBloodLow.setText("" + bloodLow);

        //
        btnStart.setText(R.string.start_measure);
        if (heart != 0
                && oxygen != 0
                && bloodHigh != 0
                && bloodLow != 0) {
            DataRepository.getInstance()
                    .saveOneKeyData(System.currentTimeMillis(), new OneKeyMeasureData(heart, oxygen, bloodHigh, bloodLow))
                    .flatMap(new Function<Object, ObservableSource<?>>() {
                        @Override
                        public ObservableSource<?> apply(Object o) throws Exception {
                            return DataRepository.getInstance().uploadData();
                        }
                    })
                    .doFinally(new Action() {
                        @Override
                        public void run() throws Exception {
                            getList();
                        }
                    })
                    .subscribe(new Observer<Object>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Object o) {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        } else {
            getList();
        }
    }

    private void getList() {
        DataRepository.getInstance()
                .homeData()
                .subscribe(new Observer<HomeData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HomeData homeData) {
                        updateUI(homeData);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void updateUI(HomeData data) {
        HeartData heartData = data.getHeartData();
        OxygenData oxygenData = data.getOxygenData();
        BloodData bloodData = data.getBloodData();
        FatigueData fatigueData = data.getFatigueData();

        //
        if (heartData.getValue() == 0) {
            textHeart.setText("--");
        } else {
            textHeart.setText("" + heartData.getValue());
        }

        //
        if (oxygenData.getValue() == 0) {
            textOxygen.setText("--");
        } else {
            textOxygen.setText("" + oxygenData.getValue());
        }

        //
        if (bloodData.getHighValue() == 0) {
            textBloodHigh.setText("--");
            textBloodLow.setText("--");
        } else {
            textBloodHigh.setText("" + bloodData.getHighValue());
            textBloodLow.setText("" + bloodData.getLowValue());
        }
        //
        textFatigue.setText(CalUtils.getFatigueDesc(fatigueData.getValue()));

//        textLastTime.setText("最近一次测量：" + data.getTimeDesc());
    }


    private void loadSetting() {
        DeviceSetting deviceSetting = RealmHelper.loadSettings();
        measureTips.setVisibility(deviceSetting.isDisdsMeasure() ? View.GONE : View.VISIBLE);
    }
}
